#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
后端配置文件
统一管理数据库连接、API配置等
"""

import os
from typing import Dict, Any, Optional, Union

class Config:
    """基础配置类"""
    
    # 应用配置
    APP_NAME = "AI测试平台API"
    APP_VERSION = "1.0.0"
    DEBUG = True
    
    # Flask配置
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'ai-test-platform-secret-key'
    HOST = '0.0.0.0'
    PORT = 5001
    
    # CORS配置
    CORS_ORIGINS = ["http://localhost:3001", "http://127.0.0.1:3001"]
    
    # 灰度模式配置
    GRAY_MODE = os.environ.get('GRAY_MODE', 'false').lower() == 'true'
    GRAY_USERNAME = 'admin'
    GRAY_PASSWORD = '123456'
    
    # MySQL配置
    MYSQL_HOST = os.environ.get('MYSQL_HOST') or 'localhost'
    MYSQL_PORT = int(os.environ.get('MYSQL_PORT') or 3306)
    MYSQL_USER = os.environ.get('MYSQL_USER') or 'idahan'
    MYSQL_PASSWORD = os.environ.get('MYSQL_PASSWORD') or 'Hb@123456'
    MYSQL_DB = os.environ.get('MYSQL_DB') or 'aiproject'
    
    @property
    def MYSQL_URI(self) -> str:
        """获取MySQL连接字符串"""
        from urllib.parse import quote_plus
        encoded_password = quote_plus(self.MYSQL_PASSWORD)
        return f"mysql+pymysql://{self.MYSQL_USER}:{encoded_password}@{self.MYSQL_HOST}:{self.MYSQL_PORT}/{self.MYSQL_DB}?charset=utf8mb4"
    
    # SQLAlchemy配置
    SQLALCHEMY_DATABASE_URI = property(MYSQL_URI)
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ECHO = False  # 生产环境设为False
    
    # API响应配置
    API_RESPONSE_FORMAT = {
        'success_format': {
            'success': True,
            'message': '',
            'data': None
        },
        'error_format': {
            'success': False,
            'message': '',
            'error': None
        }
    }

class DevelopmentConfig(Config):
    """开发环境配置"""
    DEBUG = True
    MYSQL_DB = 'aiproject_dev'
    SQLALCHEMY_ECHO = True  # 开发环境显示SQL语句
    # 开发环境默认开启灰度模式
    GRAY_MODE = os.environ.get('GRAY_MODE', 'true').lower() == 'true'

class ProductionConfig(Config):
    """生产环境配置"""
    DEBUG = False
    MYSQL_HOST = os.environ.get('PROD_MYSQL_HOST') or 'localhost'
    MYSQL_DB = 'aiproject_prod'
    PORT = int(os.environ.get('PORT') or 5001)
    SQLALCHEMY_ECHO = False
    # 生产环境默认关闭灰度模式
    GRAY_MODE = os.environ.get('GRAY_MODE', 'false').lower() == 'true'

class TestingConfig(Config):
    """测试环境配置"""
    DEBUG = True
    TESTING = True
    MYSQL_DB = 'aiproject_test'
    SQLALCHEMY_ECHO = True
    # 测试环境默认开启灰度模式
    GRAY_MODE = os.environ.get('GRAY_MODE', 'true').lower() == 'true'

# 配置映射
config_map: Dict[str, Any] = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig,
    'default': DevelopmentConfig
}

def get_config(env: Optional[str] = None) -> Config:
    """获取配置对象"""
    env = env or os.environ.get('FLASK_ENV') or 'development'
    return config_map.get(env, config_map['default'])()

# 默认配置实例
current_config = get_config()